package com.lhy.realm;

import com.lhy.dao.UserDao;
import com.lhy.entity.Permission;
import com.lhy.entity.User;
import com.lhy.service.PermissionService;
import com.lhy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：罗昊宇
 * @Package：com.realm
 * @Project：shiro-framwork
 * @name：MyReaml
 * @Date：2024/5/10 0010  19:14
 * @Filename：MyReaml
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取当前的登陆着的信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Permission> permissions = permissionService.selectByUserId(user.getUserid());
        if (permissions.size()>0){

            SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();

            List<String> stringList = permissions.stream().map(item -> item.getPercode()).collect(Collectors.toList());
            info.addStringPermissions(stringList);

            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取账号
        String username = (String) authenticationToken.getPrincipal();
        //查询
        User user=userService.selectByUsername(username);
        if (user!=null){
            ByteSource salt = ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info =new SimpleAuthenticationInfo(user,user.getUserpwd(),salt,this.getName());
            return info;

        }

        return null;
    }
}
